<template>
  <div class="biz-container">
    <table-layout :haveSider="false">
      <template #searchBox>
        <search-layout
          :formInfos="q_formInfos"
          :formDatas="q_formDatas"
          message=""
          @onFind="onFind"
          @onChangeType="onChangeType"
        ></search-layout>
      </template>
      <template #batchOperat>
        <batch-operat-btn 
          :addData="true" @onAddData="onAddData"
          :delectData="true" @onDelectData="onDelectData">
          <template #cusBtn>
            <!-- <a-button type="primary" v-print="'#printTest'" > 打印 </a-button>  -->
            <!-- <a-button type="primary" icon="vertical-align-bottom" size="small"> 自定义按钮 </a-button> -->
            <!-- <im-export></im-export> -->
          </template>
        </batch-operat-btn>
      </template>
      <template #tableList="slotData">
        <div >
          <a-list-table
            :columns="columns"
            :tableData="listdata"
            :pagination="pagination"
            :isSelecttion="true"
            :loading="loading"
            :scroll="{y:slotData.tableHeight}"
            :renderStateByField="['purOrderState']"
            @onTableChange="handleTableChange"
            @onselectChange="onselectChange"
            @onAction="onAction"
            @onTouchCell="onTouchCell"
          >
          </a-list-table>
        </div>
        
      </template>
    </table-layout>
     <saleGoodsModal ref="modal" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <editOrderModal ref="editOrder" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <editDetailModal ref="editDetail" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <viewModal ref="viewModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import saleGoodsModal from './purchaseOrderModal'
import editOrderModal from './editOrderModal'
import editDetailModal from './editDetailModal'
import viewModal from './viewModal'
import {
  getByConditions,
  getByConditionsCount,
  deleteInfo,
  pushOrder
} from './purchaseOrder'
import {
  columns,
  q_formInfos,
  q_formDatas
} from './dataConfig'


export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    saleGoodsModal,
    editOrderModal,
    editDetailModal,
    viewModal
  },
  data() {
    return {
      columns: columns,
      listdata: [],
      loading: false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '10', '50', '100'],
      },
      q_formInfos: q_formInfos,
      q_formDatas: q_formDatas,
      pData: {}, // 条件查询参数
      selectedRowKeys:[],
      selectedRows:[]
    }
  },
  computed: {},
  watch: {
    //监听路由，只要路由有变化(路径，参数等变化)都有执行下面的函数，你可以
    $route: {
        handler: function (val, oldVal) {
          //created事件触发的函数可以在这里写... 
          this.getTotal()
          this.getList(this.q_formDatas)
        },
        deep: true,
        immediate:true
    }
  },
  mounted() {
    
  },
  methods: {
    // 初始化页面时得到总数
    async getTotal() {
      let pages = ''
      pages = await getByConditionsCount(this.q_formDatas)
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal =  (showTotal) => {return `共 ${showTotal} 条`}
      }
    },
    // 初始化查询时的数据列表
    async getList(params) {
      console.log('请求列表时传入的数据', params)
      this.loading = true
      this.listdata = [] 
      let res = ''
      res = await getByConditions(params, this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
          for (let item of resdata) {
            let actionBtn= ['查看订单']
            if (item.purOrderState ==='未推送') {
              actionBtn = ['推送','编辑明细']
            }
            // if (item.deliveryState=='待收货') {
            //   actionBtn = ['收货']
            // }
            this.listdata.push({
              key: item.pid,
              action: actionBtn,
              ...item
              }
            )
          }
      } else {
        this.listdata = []
      }
      this.loading = false
    },
    // 新增按钮 点击了新增
    onAddData() {
      console.log('点击了新增')
      // this.$refs.modal.addModal()
      this.$router.push({
        name: 'addPurchaseOrder',
        params: {
          isJump:false,
          pathName:this.$route.name,
          pid:null,
          type:'add'
        } 
      })
    },
    // 关闭模态详细框
    handleModalCancel() {
    },
    // 模态详细框提交按钮
    handleModalSaveOk() {
      this.getTotal()
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction(text, record, index) {
      console.log('点击list中的操作按钮', text, record, index)
      if (text == '推送') {
        this.showPushConfirm(record,'1')
      }else if(text=='编辑明细'){
        this.$refs.editDetail.editModal(record)
      }else if(text=='删除'){
        this.showConfirm(record,'1')
        // this.$router.push({
        //   name: 'addPurchaseOrder',
        //   params: {
        //     isJump:false,
        //     pathName:this.$route.name,
        //     pid:record.pid
        //   } 
        // })
      }else if(text=='查看订单'){
        this.$refs.viewModal.showModal(record.pid,record)
      }else if(text=='收货'){

      }
    },
    showConfirm(val,type) {
      let datas=[]
      if(type=='1'){
        datas[0]=val
      }else{
        datas=val
      }
      const that = this;
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk() {
          let reqArr=[]
          let key='self'
          for (const item of datas) {
            reqArr.push(that.deleteInfos(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1' && item.data) {
                that.$message.success({ content:'采购订单'+item.data.purOrderNo+ '删除成功', duration: 3 })
              } else {
                that.$message.error({ content:'采购订单'+item.data.purOrderNo+ '删除失败，原因：'+item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content:'操作出错:'+err, duration: 3 })
          })
        },
        onCancel() {},
      });
    },
    async deleteInfos(val){
      let res = await deleteInfo(val)
      return res
    },
    //推送弹框
    showPushConfirm(val,type) {
      let datas=[]
      if(type=='1'){
        datas[0]=val
      }else{
        datas=val
      }
      const that = this;
      this.$confirm({
        title: '是否确认推送？',
        content: '推送后请提醒供应商查看',
        onOk() {
          let reqArr=[]
          let key='self'
          for (const item of datas) {
            reqArr.push(that.pushInfos(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1') {
                that.$message.success({ content:'采购订单推送成功', duration: 3 })
              } else {
                that.$message.error({ content:'采购订单推送失败，原因：'+item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content:'操作出错:'+err, duration: 3 })
          })
        },
        onCancel() {},
      });
    },
    async pushInfos(val){
      let res = await pushOrder(val)
      return res
    },
    onTouchCell(text, record, index){
      this.$refs.editOrder.editModal(record.pid)
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    // 搜索栏选择下拉select触发搜索val[0]表示选中的record中的pid,val[1]表示选中的record全部信息
    onChangeType(name, val) {
      console.log('formName',name)
      console.log('val',val)
      switch (name) {
        case 'pid': 
          if (!val[0]) {
            this.q_formDatas.pid=null
          }
          this.onFind ()
          break 
        case 'purType':
          if (!val) {
            this.q_formDatas.purType=null
          }
          this.onFind ()
          break
        case 'purOrderState':
          if (!val) {
            this.q_formDatas.purOrderState=null
          }
          this.onFind ()
          break
      }
    },
    // 查询按钮
    onFind (){
      this.pagination.current = 1
      this.getTotal()
      this.getList(this.q_formDatas)
    },
    // 多选批量操作
    onselectChange(selectedRowKeys,selectedRows ) {
      this.selectedRowKeys=selectedRowKeys
      this.selectedRows=selectedRows
    },
    onDelectData(){
      if(this.selectedRows.length){
        this.showConfirm(this.selectedRows)
      }else{
        this.$message.warning({ content:'未选择要删除的商品', duration: 3 })
      }
    }
  },
}
</script>

<style>
</style>